import { OnInit, Component, Output, EventEmitter, ViewChild, Input } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd';
import { StudentScoreService } from 'src/app/project/service/icm/icm-student-academic/score-entry/student-score.service';
import { FormBuilder, NgForm, FormGroup, Validators } from '@angular/forms';
import { OperationNotification, OperationType } from 'src/app/project/model/common/operation-notification';
import { StudentCourseGradeDTO } from 'src/app/project/model/icm/icm-student-academic/score-entry/student-course-grade.dto';
import { QueryOptions } from 'src/app/project/model/common/query-options';
import { FormUtil } from '@shared/utils/form-util';
import { format } from 'date-fns';

@Component({
  selector: 'app-score-entry-detail',
  templateUrl: './score-entry-detail.component.html',
  styles: [],
})
export class ScoreEntryDetailComponent implements OnInit {
  constructor(
    private msg: NzMessageService,
    private studentScoreService: StudentScoreService,
    private fb: FormBuilder,
  ) {
    this.validateForm = this.fb.group({
      gradePoint: ['', [Validators.required]],
      getCredit: ['', [Validators.required]],
      grade: ['', [Validators.required]],
      creditGradePoint: [{ value: '', disabled: true }],
      remark: ['', [Validators.required]],
    });
  }

  /**
   * 数据变化通知事件
   */
  @Output()
  notification = new EventEmitter<OperationNotification<StudentCourseGradeDTO>>();

  /**
   * form组件
   */
  @ViewChild('myForm', { static: false })
  public myForm: NgForm;

  /**
   * 表单
   */
  validateForm: FormGroup;

  /**
   * 是否预览
   */
  isPreView = false;

  /**
   * 表单窗体打开/关闭控制
   */
  isVisible = false;

  /**
   * 调用后台API标志
   */
  loading = false;

  /**
   * 分页参数初始化
   */
  queryOptions: QueryOptions = {
    page: 0,
    size: 20,
    sort: 'year,desc',
  };

  /**
   * 学生选课信息
   */
  studentCourseGrade: StudentCourseGradeDTO = {
    id: null,
    academyName: null,
    courseCode: null,
    courseName: null,
    studentCode: null,
    studentName: null,
    className: null,
    credit: null,
    courseType: null,
    year: '',
    nextYear: null,
    termType: '',
    evaluationMode: null,
    property: null,
    grade: null,
    getCredit: null,
    gradePoint: null,
    creditGradePoint: null,
    isCorrect: null,
    remark: null,
  };

  /**
   * 修改窗口状态
   */
  handleCancel() {
    this.isVisible = false;
    FormUtil.resetForm(this.myForm.form);
  }

  /**
   * 修改或新增学生课程成绩信息
   * @param isPreView 是否预览
   * @param item 学生课程成绩信息
   */
  edit(isPreView: boolean, item: StudentCourseGradeDTO) {
    this.isPreView = isPreView;

    this.studentCourseGrade = this.initStudentCourseGrade(item);
    this.isVisible = true;
  }

  /**
   * 初始化课程
   */
  initStudentCourseGrade(item: StudentCourseGradeDTO): StudentCourseGradeDTO {
    return {
      id: item ? item.id : null,
      year: item ? item.year : null,
      nextYear: item ? Number.parseInt(item.year, 10) + 1 : null,
      academyName: item ? item.academyName : null,
      termType: item ? item.termType : null,
      courseCode: item ? item.courseCode : null,
      courseName: item ? item.courseName : null,
      studentCode: item ? item.studentCode : null,
      studentName: item ? item.studentName : null,
      className: item ? item.className : null,
      credit: item ? item.credit : null,
      courseType: item ? item.courseType : null,
      evaluationMode: item ? item.evaluationMode : null,
      property: item ? item.property : null,
      grade: item ? item.grade : null,
      getCredit: item ? item.getCredit : null,
      gradePoint: item ? item.gradePoint : null,
      creditGradePoint: item ? item.creditGradePoint : null,
      isCorrect: item ? item.isCorrect : null,
      remark: item ? item.remark : null,
    };
  }

  /**
   * 根据成绩计算绩点
   */
  calculateGradePoint(studentCourseGrade: StudentCourseGradeDTO, boo: boolean) {
    if (boo) {
      // 分数
      const grade = Number.parseInt(studentCourseGrade.grade, 10);
      studentCourseGrade.gradePoint = grade >= 60 ? (grade - 60) * 0.1 + 1 : 0;
    } else {
      // 成绩
      studentCourseGrade.gradePoint =
        studentCourseGrade.grade === '优秀'
          ? 4
          : studentCourseGrade.grade === '良好'
          ? 3
          : studentCourseGrade.grade === '中等'
          ? 2
          : studentCourseGrade.grade === '及格'
          ? 1
          : 0;
    }
  }

  /**
   * 计算学分绩点
   */
  calculationCreditGradePoint() {
    this.studentCourseGrade.creditGradePoint =
      this.studentCourseGrade.getCredit != null && this.studentCourseGrade.gradePoint != null
        ? this.studentCourseGrade.getCredit * this.studentCourseGrade.gradePoint
        : null;
  }

  /**
   * 保存前验证数据
   */
  beforeSave() {
    if (this.studentCourseGrade.grade === null) {
      this.msg.error('未输入成绩');
      return false;
    }
    if (!this.studentCourseGrade.getCredit && this.studentCourseGrade.getCredit !== 0) {
      this.msg.error('未输入取得学分');
      return false;
    }
    if (!this.studentCourseGrade.gradePoint && this.studentCourseGrade.gradePoint !== 0) {
      this.msg.error('未输入取得绩点');
      return false;
    }
    return true;
  }

  /**
   * 保存
   */
  save() {
    if (!this.beforeSave()) {
      return;
    }
    this.loading = true;
    if (this.studentCourseGrade.isCorrect === false) {
      this.studentCourseGrade.isCorrect = true;
      // 未批改成绩
      this.studentScoreService.complete(this.studentCourseGrade.id, this.studentCourseGrade).subscribe(
        data => this.afterItemSaved(data, OperationType.CREATE),
        () => this.msg.error('批改成绩失败，请重试'),
        () => {
          this.afterCallCompleted();
          this.msg.success('批改成功!');
        },
      );
    } else {
      // 修改已批改的成绩
      this.studentScoreService.update(this.studentCourseGrade.id, this.studentCourseGrade).subscribe(
        data => this.afterItemSaved(data, OperationType.CREATE),
        () => this.msg.error('修改成绩失败，请重试'),
        () => {
          this.afterCallCompleted();
          this.msg.success('修改成功!');
        },
      );
    }
  }

  /**
   * 数据保存后的通用操作
   *
   * @param data 保存的数据
   * @param operation 操作类型
   */
  private afterItemSaved(data: StudentCourseGradeDTO, operation: OperationType): void {
    this.loading = false;
    this.handleCancel();
    this.notification.emit({
      operation,
      data,
    });
  }

  /**
   * API调用完成后的操作
   */
  private afterCallCompleted(): void {
    this.loading = false;
  }

  ngOnInit() {}
}
